﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using SyndicateDAO.DAO;
using SyndicateDAO.DatabaseObject;

namespace SyndicateBusiness.Classes
{
    public class ResultBL
    {
        private ResultDAO ResultDAO = new ResultDAO();

        private DrawDAO DrawDAO = new DrawDAO();

        private List<string> DownloadResults(string url)
        {
            List<string> results = new List<string>(); 

            StringBuilder sb = new StringBuilder();

            // used on each read operation
            byte[] buf = new byte[8192];

            // prepare the web page we will be asking for
            HttpWebRequest request = (HttpWebRequest)
                WebRequest.Create(url);

            // execute the request
            HttpWebResponse response = (HttpWebResponse)
                request.GetResponse();

            // we will read data via the response stream
            Stream resStream = response.GetResponseStream();

            string tempString = null;
            int count = 0;

            do
            {
                // fill the buffer with data
                count = resStream.Read(buf, 0, buf.Length);

                // make sure we read some data
                if (count != 0)
                {
                    // translate from bytes to ASCII text
                    tempString = Encoding.ASCII.GetString(buf, 0, count);

                    // continue building the string
                    sb.Append(tempString);
                }
            }
            while (count > 0); // any more data to read?

            // print out page source
           string text = sb.ToString();

           results = Regex.Split(text, "\n").ToList();

           results.RemoveAt(0);

           results.RemoveAll(item => item == String.Empty);

           return results;

        }

        public string GetResultString(int dId)
        {
            result r = this.ResultDAO.SelectAllByDrawId(dId).FirstOrDefault();

            if (r != null)
                return r.numbers;
            else
                return "";
        }

        public string GetResultStringRaffle(int dId)
        {
            result r = this.ResultDAO.SelectAllByDrawId(dId).FirstOrDefault();

            if (r != null)
                return r.raffle != null ? r.raffle : "";
            else
                return "";
        }

        public void FindResults(int sId, string type = draw.drawType.LOTTO)
        {

            var pendingDraws = DrawDAO.SelectAllBySyndicateId(sId).Where(d => d.status == draw.drawstatus.PENDING && d.type == type);

            List<string> results = new List<string>();

            switch (type)
            {
                case draw.drawType.LOTTO:
                    results = DownloadResults("http://www.national-lottery.co.uk/player/lotto/results/downloadResultsCSV.ftl");

                    foreach (draw d in pendingDraws)
                    {
                        if (FindSingleResult(d.id, results))
                        {
                            d.status = draw.drawstatus.FINISHED;

                            DrawDAO.Update();

                        }
                    }



                    break;
                case draw.drawType.EUROMILLIONS:
                    results = DownloadResults("http://www.national-lottery.co.uk/player/euromillions/results/downloadResultsCSV.ftl");
                    
                    foreach (draw d in pendingDraws)
                    {
                        if (FindSingleResultEuro(d.id, results))
                        {
                            d.status = draw.drawstatus.FINISHED;

                            DrawDAO.Update();

                        }
                    }
                    break;
            }
            

        }



        public bool FindSingleResult(int dId, List<string> results, string type = draw.drawType.LOTTO)
        {
            bool resultFound = false;

            draw draww = DrawDAO.SelectAll().Where(d => d.id == dId && d.isActivated).FirstOrDefault();

            if (draww != null)
            {              

                foreach (string item in results)
                {
                    ResultObject ro = new ResultObject(item);

                    if (draww.drawdate.ToString("dd-MMM-yyyy") == ro.DrawDate)
                    {
                        result r = this.ResultDAO.SelectAllByDrawId(dId).FirstOrDefault();

                        if (r == null)
                        {
                            r = new result();
                            r.drawId = dId;
                            r.numbers = String.Join(",", ro.ResultListWithBonus.ToArray());
                            r.dateDownloaded = DateTime.Now;
                            r.raffle = ro.Raffle;
                            this.ResultDAO.InsertResult(r);
                        }
                        else
                        {
                            r.numbers = String.Join(",", ro.ResultListWithBonus.ToArray());
                            r.dateDownloaded = DateTime.Now;
                            r.raffle = ro.Raffle;
                            this.ResultDAO.Update();
                        }

                        resultFound = true;
                        break;


                    }

                }
            }

            return resultFound;
        }

        public bool FindSingleResultEuro(int dId, List<string> results, string type = draw.drawType.LOTTO)
        {
            bool resultFound = false;

            draw draww = DrawDAO.SelectAll().Where(d => d.id == dId && d.isActivated).FirstOrDefault();

            if (draww != null)
            {

                foreach (string item in results)
                {
                    ResultObjectEuroMIllions ro = new ResultObjectEuroMIllions(item);

                    if (draww.drawdate.ToString("dd-MMM-yyyy") == ro.DrawDate)
                    {
                        result r = this.ResultDAO.SelectAllByDrawId(dId).FirstOrDefault();

                        if (r == null)
                        {
                            r = new result();
                            r.drawId = dId;
                            r.numbers = String.Join(",", ro.Results.ToArray()) + "," + String.Join(",", ro.ResultsLuckyStars.ToArray());
                            r.raffle = ro.Raffle;
                            r.dateDownloaded = DateTime.Now;
                            //r.raffle = 
                            this.ResultDAO.InsertResult(r);
                        }
                        else
                        {
                            r.numbers = String.Join(",", ro.Results.ToArray()) + "," + String.Join(",", ro.ResultsLuckyStars.ToArray());
                            r.raffle = ro.Raffle;
                            r.dateDownloaded = DateTime.Now;
                            this.ResultDAO.Update();
                        }

                        resultFound = true;
                        break;


                    }

                }
            }

            return resultFound;
        }


    }
}
